//
//  MainPageViewController.m
//  iRMAP
//
//  Created by Ryan Enguero on 3/27/14.
//  Copyright (c) 2014 engueroryan. All rights reserved.
//

#import "MainPageViewController.h"

#import "User.h"

#import "ParserClass.h"

#import "PostClass.h"

#import "Company.h"

#import "UiManager.h"

#import "DevicesTableViewController.h"
#import "AlarmsTableViewController.h"

#import "Devices.h"

#import "loadingView.h"

#import "MainPageCell.h"

#define kBgQueue dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)

@interface MainPageViewController ()

@end

@implementation MainPageViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    
    UILabel* lbNavTitle = [[UILabel alloc] initWithFrame:CGRectMake(0,50,320,40)];
    //lbNavTitle.textAlignment = UITextAlignmentLeft;
    lbNavTitle.text = NSLocalizedString(@"COMPANY",@"");
    [lbNavTitle setTextColor:[UIColor whiteColor]];
    [lbNavTitle setFont:[UIFont fontWithName:@"HelveticaNeue-Light" size:23.0f]];
    self.navigationItem.titleView = lbNavTitle;
    
    // Do any additional setup after loading the view from its nib.
    
//    UITabBarController *tabBar = [[UITabBarController alloc] init];
//    
//    self.devicesTableView = [[DevicesTableViewController alloc] initWithNibName:@"DevicesTableViewController" bundle:nil];
//    
//    self.alarmsTableView = [[AlarmsTableViewController alloc] initWithNibName:@"AlarmsTableViewController" bundle:nil];
//    
//    tabBar.viewControllers = @[self.devicesTableView,self.alarmsTableView];
//    
//    [self presentViewController:tabBar animated:YES completion:nil];
    
    
    User *user = [[ParserClass sharedItems] userdetails][0];
    
    
    
    NSDictionary* listOfCompaniesJson = [[PostClass sharedItems] getCompanies:[user sessionID]];
    
    [[ParserClass sharedItems] listOfCompanies:listOfCompaniesJson];
    
    NSLog(@"Parse Company Details = %@", [[ParserClass sharedItems] companyDetails]);

    
 
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}




#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    //#warning Potentially incomplete method implementation.
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    //#warning Incomplete method implementation.
    // Return the number of rows in the section.
    return [[[ParserClass sharedItems] companyDetails] count];
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
        // Configure the cell...
    
    
    
    
    static NSString *cellIdentifier = @"Cell";
    
    MainPageCell *cell = (MainPageCell*)[tableView dequeueReusableCellWithIdentifier:cellIdentifier];

    
    if (cell == nil) {
        
        NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"MainPageCell" owner:self options:nil];
        cell = [nib objectAtIndex:0];
    }
    

    
    Company *company = [[ParserClass sharedItems] companyDetails][indexPath.row];
    
    
    cell.lblList.text = [company companyName];
    [cell.textLabel setTextColor:[UIColor whiteColor]];
    [cell setBackgroundColor:[UIColor colorWithRed:82.0/255.0 green:82.0/255.0 blue:82.0/255.0 alpha:1.0]];
    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
    
    return cell;
    
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 60.0;
}



#pragma mark - Table view delegate

// In a xib-based application, navigation from a table can be handled in -tableView:didSelectRowAtIndexPath:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    
    MainPageCell *cell = (MainPageCell*) [tableView cellForRowAtIndexPath:indexPath];
    
    [cell.imgLoadingMini setAlpha:1.0];
    
//    NSArray *xib = [[NSBundle mainBundle] loadNibNamed:@"loadingView" owner:self options:nil];
//    loadingView * loading = [xib objectAtIndex:0];
//    
//    [loading setFrame:CGRectMake(0, -130, 93, 47)];
//    
//    //[loading setBackgroundColor:[UIColor redColor]];
//    
//    
//    [loading.imgLoading2 setAlpha:1.0];
//    [loading.imgLoading setAlpha:0.0];
//    
//    
//    [self.view addSubview:loading];
    
   //
    //    [[UiManager sharedItems] slideLeft];
    
        Company *company = [[ParserClass sharedItems] companyDetails][indexPath.row];
        
        User *user = [[ParserClass sharedItems] userdetails][0];

    
    
        
    dispatch_async(kBgQueue, ^{

        [self.tblList1 setUserInteractionEnabled:YES];
        //Devices *devices = [[ParserClass sharedItems] deviceDetails][indexPath.row];
    
            NSDictionary* json = [[PostClass sharedItems] getDevicesSessionID:[user sessionID] andDomainID:[company domainId]];
    
    if ([[[json objectForKey:@"response"] objectForKey:@"status"] isEqualToString:@"success"]) {
        //  self.delegate = [UiManager sharedItems].devicesTableView;
        dispatch_async(dispatch_get_main_queue(), ^{

        self.delegate = [UiManager sharedItems].alarmsTableView;
        
        [self.delegate getSessionID:[user sessionID] andDomainID:[company domainId] andDeviceID:nil];
        
        [[ParserClass sharedItems] listOfDevices:json];
        
        [[ParserClass sharedItems] getDomainID:[company domainId]];
        
        [[UiManager sharedItems] slideLeft];
            
        //[loading removeFromSuperview];
        
        NSLog(@"devices = %@", json);
        [cell.imgLoadingMini setAlpha:0.0];
        
                    });

    }else{
        
        //[loading removeFromSuperview];
        [self.tblList1 setUserInteractionEnabled:NO];
        dispatch_async(dispatch_get_main_queue(), ^{

        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:[NSString stringWithFormat:@"%@",[[[json objectForKey:@"response"] objectForKey:@"error"] objectForKey:@"code"]] message:[NSString stringWithFormat:@"%@",[[[json objectForKey:@"response"] objectForKey:@"error"] objectForKey:@"message"]] delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil];
        
        [alertView show];
    });
        
    }
        
        });
 //   });
    
    

}


- (IBAction)logOutAction:(id)sender {
    
    User *user = [[ParserClass sharedItems] userdetails][0];
    
    NSDictionary *logOutDict = [[PostClass sharedItems] logOutWithSessionID:[user sessionID]];
    
    if ([[[logOutDict objectForKey:@"response"] objectForKey:@"status"] isEqualToString:@"success"]) {
        [[ParserClass sharedItems] emptyData];
        
        [[UiManager sharedItems] logOut];
    }else{
    
//        UIAlertView *alertLogOut = [[UIAlertView alloc] initWithTitle:@"Error" message:@"Log Out UnAvailable" delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil];
//        
//        [alertLogOut show];
        
        [[ParserClass sharedItems] emptyData];
        
        [[UiManager sharedItems] logOut];

    }
    
    
}


@end
